﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using RepRef;
using System.Data; 

public partial class MasterPages_CoverReport : System.Web.UI.MasterPage
{
    IsimpleWcfClient reportProxy;
    RepRef.ModuleManager modMgr;
    IList<RepRef.ClassInfo> classInfoCollection = null;
    string strXMLPath;    
    public static bool showImage = false;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["RptXMLPath"] != null)
        {
            strXMLPath = Session["RptXMLPath"].ToString();
        }       
        if (!IsPostBack)
        {
            lnkCloud.HRef = ConfigurationManager.AppSettings["CloudPage"] + "?rptLink=" + strXMLPath;
            lnkDash.HRef = ConfigurationManager.AppSettings["InitialPage"];
            lnkAgg.HRef = ConfigurationManager.AppSettings["AggregatePage"];
            PopulateTree(strXMLPath);
        }
       
    }

    protected void PopulateTree(string strXMLPath)
    {
        reportProxy = new IsimpleWcfClient();       
        string ModName = string.Empty;
        string NsName = string.Empty;
        string[] strArr = null;
        // Bettre host bthis XML file in IIS and access it through http
        //or use webclient

        try
        {
            modMgr = reportProxy.ParseXmlObject(strXMLPath);
            TreeNode tvNode;
            TreeNode tvNodeLevel2;
            //TreeNode tvNodeLevel3;
            foreach (RepRef.ModuleItem mItem in modMgr.ModuleItemCollection)
            {
                tvNode = new TreeNode();
                tvwModular.Nodes.Add(tvNode);
                tvNode.Text = mItem.ModuleName;

                foreach (RepRef.NameSpaceItem nItem in mItem.NameSpaceItemCollection)
                {
                    string strNsCovPer = string.Empty;
                    tvNodeLevel2 = new TreeNode();
                    tvNode.ChildNodes.Add(tvNodeLevel2);
                    if (nItem.NamespaceCovPercentage != 0.0)
                    {
                        strNsCovPer = string.Format("{00:#.##}", nItem.NamespaceCovPercentage);
                    }
                    else
                    {
                        strNsCovPer = nItem.NamespaceCovPercentage.ToString();
                    }
                    tvNodeLevel2.Text = nItem.NameSpaceName + " (" + strNsCovPer + "%)";


                    //foreach (ClassItem clsItem in nItem.ClassItemCollection)
                    //{
                    //    tvNodeLevel3 = new TreeNode();
                    //    tvNodeLevel2.ChildNodes.Add(tvNodeLevel3);
                    //    tvNodeLevel3.Text = clsItem.ClassName; 
                    //}
                }

            }
            if (tvwModular.Nodes.Count > 0)
            {
                if (!string.IsNullOrEmpty(tvwModular.Nodes[0].Text))
                {

                    if (tvwModular.Nodes[0].ChildNodes.Count > 0)
                    {
                        strArr = tvwModular.Nodes[0].ChildNodes[0].Text.Split('(');
                        if (strArr.Length > 0)
                        {
                            NsName = strArr[0].Trim().ToString();
                        }

                        if (Session["ClsCovParameters"] != null)
                        {
                            if (Session["DfltNamespace"] != null)
                            {
                                string[] arrClsCovPrs = Session["ClsCovParameters"].ToString().Split(',');
                                PopulateClassCoverage(arrClsCovPrs[0].ToString(), Session["DfltNamespace"].ToString(), strXMLPath);
                            }
                            else
                            {
                                string[] arrClsCovPrs = Session["ClsCovParameters"].ToString().Split(',');
                                PopulateClassCoverage(arrClsCovPrs[0].ToString(), arrClsCovPrs[1].ToString(), strXMLPath);
                            }
                            //Session.Abandon();
                        }
                        else
                        {
                            PopulateClassCoverage(tvwModular.Nodes[0].Text, NsName, strXMLPath);
                        }
                    }
                }

            }
        }
        catch (Exception ex)
        {
        }


    }
    protected void tvwModular_SelectedNodeChanged(object sender, EventArgs e)
    {
        if (tvwModular.SelectedNode != null)
        {
            string[] strArr = null;
            string namespaceName = string.Empty;
            string moduleName = string.Empty;


            if (tvwModular.SelectedNode.ChildNodes.Count == 0)
            {
                moduleName = tvwModular.SelectedNode.Parent.Text;

                strArr = tvwModular.SelectedNode.Text.Split('(');
                if (strArr != null)
                {
                    namespaceName = strArr[0].Trim().ToString();

                    if (!string.IsNullOrEmpty(moduleName) && !string.IsNullOrEmpty(namespaceName))
                    {
                        //PopulateClassCoverage(moduleName, namespaceName);
                        if (Session["DfltNamespace"] != null)
                        {
                            Session["ClsCovParameters"] = moduleName + "," + Session["DfltNamespace"].ToString();
                        }
                        else
                        {
                            Session["ClsCovParameters"] = moduleName + "," + namespaceName;
                        }
                    }
                    //Server.Transfer(ConfigurationManager.AppSettings["NmsClsAggregatePage"] + "?mod1=" + moduleName + "&nName=" + namespaceName);
                    Response.Redirect(ConfigurationManager.AppSettings["NmsClsAggregatePage"] + "?mod1=" + moduleName + "&nName=" + namespaceName);
                }
            }


            if (tvwModular.SelectedNode.Depth == 0)
            {
                moduleName = tvwModular.SelectedNode.Text;

                //Server.Transfer(ConfigurationManager.AppSettings["AggregatePage"] + "?mod=" + moduleName);
                string[] dfltNms = tvwModular.SelectedNode.ChildNodes[0].Text.Split('(');
                Session["DfltNamespace"] = dfltNms[0].Trim().ToString();
                Response.Redirect(ConfigurationManager.AppSettings["AggregatePage"] + "?mod=" + moduleName);
            }
        }
    }

    protected void PopulateClassCoverage(string ModName, string NSName, string strXMLPath)
    {
        try
        {
            reportProxy = new IsimpleWcfClient();
            modMgr = reportProxy.ParseXmlObject(strXMLPath);
            classInfoCollection = reportProxy.GetClassInfo(ModName, NSName, strXMLPath);
            ViewState["modName"] = ModName;
            ViewState["nsName"] = NSName;

            DataTable dtTable = CreateDataTable(classInfoCollection);
            Session["ClsDataTable"] = dtTable;
            if (classInfoCollection.Count > 0)
            {
                lblClsNamespace.Text = "(" + classInfoCollection[0].NamespaceName + ")";
            }
            DataView dv = new DataView(dtTable);
            dv.Sort = "CovPercentage ASC";
            gvClassCoverage.DataSource = dv;
            gvClassCoverage.DataBind();
            Session["DfltNamespace"] = null;
            //Session["ClsCovParameters"] = null; 
        }
        catch (Exception ex)
        {
        }

    }

    public string TruncateDouble(double dblValue)
    {
        string strPercent = string.Format("{0:0.##}", dblValue);
        return strPercent + "%";
    }

    protected DataTable CreateDataTable(IList<ClassInfo> clsInfoColln)
    {

        DataTable dtTable = new DataTable();
        dtTable.Columns.Add("Classname", typeof(string));
        dtTable.Columns.Add("CovPercentage", typeof(double));

        foreach (ClassInfo clsInfo in clsInfoColln)
        {
            DataRow dtRow = dtTable.NewRow();
            dtRow["Classname"] = clsInfo.Classname;
            dtRow["CovPercentage"] = clsInfo.CovPercentage;

            dtTable.Rows.Add(dtRow);
        }
        return dtTable;
    }
    protected void AddSortImage(GridViewRow HeaderRow, int colIndex)
    {
        Image sortImage = new Image();       
        sortImage.CssClass = "SortImageStyle";
        //ViewState["SortDirection"] = GetSortDirection(column);
        if (showImage) // this is a boolean variable which should be false 
        {            //  on page load so that image wont show up initially.


            if (ViewState["SortDirection"] != null)
            {
                if (ViewState["SortDirection"].ToString() == "ASC")
                {

                    sortImage.ImageUrl = "/CoverageReport/App_Themes/ReportThemes/images/White_GrayDown.png";
                    sortImage.AlternateText = " Ascending Order";
                }

                else
                {
                    sortImage.ImageUrl = "/CoverageReport/App_Themes/ReportThemes/images/White_GrayUp.png";
                    sortImage.AlternateText = " Descending Order";
                }

                HeaderRow.Cells[colIndex].Controls.Add(sortImage);
            }
        }

    }

    private string GetSortDirection(string column)
    {

        // By default, set the sort direction to ascending.
        string sortDirection = "ASC";

        // Retrieve the last column that was sorted.
        string sortExpression = ViewState["SortExpression"] as string;

        if (sortExpression != null)
        {
            // Check if the same column is being sorted.
            // Otherwise, the default value can be returned.
            if (sortExpression == column)
            {
                string lastDirection = ViewState["SortDirection"] as string;
                if ((lastDirection != null) && (lastDirection == "ASC"))
                {
                    sortDirection = "DESC";
                }
            }
        }

        // Save new values in ViewState.
        ViewState["SortDirection"] = sortDirection;
        showImage = true;
        ViewState["SortExpression"] = column;

        return sortDirection;
    }
    private int findColumnIndex(string accessibleHeaderText)
    {
        for (int index = 0; index < gvClassCoverage.Columns.Count; index++)
        {
            if (String.Compare(gvClassCoverage.Columns[index].SortExpression, accessibleHeaderText, true) == 0)
            {
                return index;
            }
        }
        return -1;
    }
    protected void gvClassCoverage_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (Session["ClsDataTable"] != null)
        {
            DataTable dtTable = (DataTable)Session["ClsDataTable"];
            if (dtTable != null)
            {
                dtTable.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
                gvClassCoverage.DataSource = dtTable;
                gvClassCoverage.DataBind();
            }
        }
    }
    protected void gvClassCoverage_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        //sortColumnIndex = GetSortColumnIndex();
        {
            string sortExprn = string.Empty;
            if (ViewState["SortExpression"] != null)
            {
                sortExprn = ViewState["SortExpression"].ToString();
            }
            int index = findColumnIndex(sortExprn);
            AddSortImage(e.Row, index);

        }
    }
    protected void gvClassCoverage_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        string mName = string.Empty;
        string nsName = string.Empty;
        if (ViewState["modName"] != null)
        {
            mName = ViewState["modName"].ToString();
        }
        if (ViewState["nsName"] != null)
        {
            nsName = ViewState["nsName"].ToString();
        }
        Session["ClsCovParameters"] = mName + "," + nsName;
        switch (e.CommandName.ToLower())
        {
            case "openpage":
                int rowIndex;
                if (int.TryParse(e.CommandArgument.ToString(), out rowIndex))
                {
                    LinkButton lb = (LinkButton)gvClassCoverage.Rows[rowIndex].FindControl("lnkClass");
                    Label hdnLbl = (Label)gvClassCoverage.Rows[rowIndex].FindControl("hndClsName");                    
                    string strPath = HttpContext.Current.Request.ApplicationPath + "/ContentPages/ClassLvlMethodReport.aspx?mod1=" + mName + "&nName=" + nsName + "&clsName=" + hdnLbl.Text + "&rptLink=" + strXMLPath;
                    //Server.Transfer(strPath);
                    Response.Redirect(strPath);
                }
                break;
        }
    }

    protected string TruncateFewCharacters(string ClassName)
    {
        string properString = string.Empty;
        properString = ClassName.Replace("<", "&lt");
        properString = properString.Replace(">", "&gt");
        return WrappableText(properString);
        //return properString;
        
    }
    protected static string WrappableText(string source)
    {
        //string nwln = Environment.NewLine;
        //string modString = "<p>" +
        //    source.Replace(nwln + nwln, "</p><p>")
        //    .Replace(nwln, "<br />") + "</p>";

        if (source.Length > 40)
        {
            string strTemp = source.Substring(0, 40);
            return strTemp + "<b> ...</b>";
        }
        else
        {
            return source;
        }

    }
}
